package com.whatech.mall.order.controller;

import com.whatech.mall.order.exception.OrderException;
import com.whatech.mall.order.feignclient.ProductServiceFeignClient;
import com.whatech.mall.order.feignclient.UserServiceFeignClient;
import com.whatech.mall.order.model.dto.OrderDTO;
import com.whatech.mall.order.model.dto.messaging.OrderAddBonusMessageDTO;
import com.whatech.mall.order.model.dto.productservice.ProductDTO;
import com.whatech.mall.order.model.dto.userservice.UserDTO;
import com.whatech.mall.order.model.entity.Order;
import com.whatech.mall.order.model.form.OrderCreateForm;
import com.whatech.mall.order.mq.producer.RabbitProducer;
import com.whatech.mall.order.service.OrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * 订单Controller。
 */
@RestController
@RequestMapping("/order")
// 使用Lombok的特性去除IDE的红色警告
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class OrderController {

    /*private RestTemplate restTemplate;*/
    private final UserServiceFeignClient userServiceFeignClient;
    private final ProductServiceFeignClient productServiceFeignClient;
    private final OrderService orderService;
    private final RabbitProducer rabbitProducer;

    /**
     * 下单接口，调用'商品服务'获取商品信息，调用'用户服务'获取用户信息。
     */
    @PostMapping("/create")
    public OrderDTO create(OrderCreateForm orderCreateForm) {
        // 1. 根据用户ID查询用户信息（调用会员服务）
        /*String userUrl = "http://user-service/user/query/" + orderCreateForm.getUserId();
        UserDTO userDTO = restTemplate.getForObject(userUrl, UserDTO.class);*/
        UserDTO userDTO = userServiceFeignClient.findUserById(orderCreateForm.getUserId());
        if (userDTO == null) {
            throw new OrderException("user service invoke error, user not found");
        }

        // 2. 根据商品ID查询商品信息（调用商品服务）
        /*String productUrl = "http://product-service/product/query/" + orderCreateForm.getProductId();
        ProductDTO productDTO = restTemplate.getForObject(productUrl, ProductDTO.class);*/
        ProductDTO productDTO = productServiceFeignClient.findProductById(orderCreateForm.getProductId());
        if (productDTO == null) {
            throw new OrderException("product service invoke error, product not found");
        }

        // 3. 模拟生成订单
        Order order = new Order();
        order.setUserId(orderCreateForm.getUserId());
        order.setProductId(orderCreateForm.getProductId());
        order.setBuyCount(orderCreateForm.getBuyCount());
        order.setUnitPrice(productDTO.getPrice());
        order.setTotalPrice(orderCreateForm.getBuyCount() * productDTO.getPrice());
        order.setStatus(0);
        order.setCreateTime(new Date());
        Order saved = orderService.save(order);

        // 4. 下单成功，发送消息到MQ，营销服务订阅此消息、添加积分
        rabbitProducer.sendOrderAddBonusMessage(OrderAddBonusMessageDTO.builder()
                .orderId(saved.getId())
                .userId(order.getUserId())
                .totalPrice(order.getTotalPrice())
                .bonus((int) order.getTotalPrice())
                .build());

        OrderDTO orderDTO = new OrderDTO();
        orderDTO.setUsername(userDTO.getUsername());
        orderDTO.setProductName(productDTO.getName());
        BeanUtils.copyProperties(saved, orderDTO);

        return orderDTO;
    }

    /**
     * 模拟跨微服务调用获取用户。
     */
    @GetMapping("/getUser")
    public String getUser(UserDTO userDTO) {
        return userServiceFeignClient.getUser(userDTO) ? "get success" : "get failure";
    }

}
